<template>
  <el-card>
    <div class="mb-4">
      <el-button type="primary" @click="handleAddNotice">发布新通知</el-button>
    </div>
    
    <el-table :data="noticeList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="title" label="通知标题" min-width="200" />
      <el-table-column prop="content" label="内容摘要" min-width="300">
        <template #default="{ row }">
          {{ row.content.slice(0, 50) }}...
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="发布时间" width="180" />
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button size="small" @click="handleEditNotice(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDeleteNotice(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="通知内容" prop="content">
          <el-input type="textarea" v-model="form.content" placeholder="请输入通知内容" rows="6" />
        </el-form-item>
        <el-form-item label="通知对象" prop="userIds">
          <el-select
            v-model="form.userIds"
            placeholder="请选择接收人"
            multiple
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.userName"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitNotice">确认</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  listNotice, 
  addNotice, 
  updateNotice, 
  deleteNotice 
} from '@/api/notice';
import { listUsertable } from '@/api/usertable';
import { useRouter } from 'vue-router';

const router = useRouter();
const noticeList = ref([]);
const userList = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const form = reactive({
  id: null,
  title: '',
  content: '',
  userIds: []
});
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }],
  userIds: [{ required: true, message: '请选择接收人', trigger: 'change' }]
};

// 获取通知列表
const getNoticeList = async () => {
  try {
    const res = await listNotice();
    noticeList.value = res;
  } catch (error) {
    ElMessage.error(`获取通知列表失败: ${error.message}`);
  }
};

// 获取用户列表
const getUserList = async () => {
  try {
    const res = await listUsertable();
    userList.value = res;
  } catch (error) {
    ElMessage.error('获取用户列表失败');
  }
};

// 新增通知
const handleAddNotice = () => {
  dialogTitle.value = '新增通知';
  form.id = null;
  form.title = '';
  form.content = '';
  form.userIds = [];
  dialogVisible.value = true;
};

// 编辑通知
const handleEditNotice = (row) => {
  dialogTitle.value = '编辑通知';
  form.id = row.id;
  form.title = row.title;
  form.content = row.content;
  form.userIds = row.userIds || []; // 处理可能为null的情况
  dialogVisible.value = true;
};

// 删除通知
const handleDeleteNotice = (row) => {
  ElMessageBox.confirm('确认删除该通知?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteNotice(row.id);
    ElMessage.success('删除成功');
    getNoticeList();
  }).catch(() => ElMessage.info('已取消删除'));
};

// 提交通知
const submitNotice = async () => {
  await formRef.value.validate();
  try {
    if (form.id) {
      await updateNotice(form);
      ElMessage.success('通知更新成功');
    } else {
      await addNotice(form);
      ElMessage.success('通知发布成功');
    }
    dialogVisible.value = false;
    getNoticeList();
  } catch (error) {
    ElMessage.error(`操作失败: ${error.message}`);
  }
};

onMounted(() => {
  getNoticeList();
  getUserList();
});
</script>